package com.datastructure.test.ysf;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Scanner;

public class YSF {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            int num = scanner.nextInt();
            LinkedList<Integer> list = new LinkedList<>();
            for (int i = 0; i < num; i++)
                list.add(i);
            int position = 0;
            int temp = 0;
            while (list.size() > 1) {
                position += 2;
                if (position > list.size() - 1)
                    position = position % list.size();
                temp = list.indexOf(list.get(position));
                list.remove(position);
                position = temp;
            }
            System.out.println(list.get(0));
        }
    }

    public int ysf (int n, int m) {
        // write code here
        if(n<0||n<m){
           return -1;
        }
        //形成环形链表
        ListNode temp = null;
        ListNode cur = null;
        ListNode first = null;
        ListNode lastListNode = null;
        boolean flag = true;
        while (n>0){
            cur = new ListNode(n);
            cur.next=temp;
            temp=cur;
            if(flag){
                first=cur;
                flag=false;
            }
            n--;
        }
        //形成环形链表
        first.next=temp;
        //开始遍历循环的上一个节点
        lastListNode=first;
        //开始循环遍历的当前节点
        cur = first.next;
        while (true){
            for(int i = 0;i<m-1;i++){
                cur=cur.next;
                lastListNode=lastListNode.next;
            }
            lastListNode.next=cur.next;
            cur=cur.next;
            if(lastListNode==cur){
                return cur.val;
            }
        }
    }

    public int LastRemaining_Solution(int n, int m) {
        if (n <= 0) return -1;
        int index = 0;
        for (int i=2; i<=n; ++i) {
            index = (index + m) % i;
        }
        return index;
    }
}

class ListNode{
    int val;
    ListNode next;

    public ListNode(int val) {
        this.val = val;
    }
}
